﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace DnPakExplorer.Controls {
	public partial class ToggleButton : UserControl {

		private Image mOnBackground;
		private Image mOffBackground;
		private bool mIsOn;
		private TextFormatFlags mTextFormatFlags = TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine;

		public event EventHandler OnToggleChanged;

		[Browsable(true)]
		public Image OnBackground {
			get { return mOnBackground; }
			set {
				mOnBackground = value;
				Invalidate();
			}
		}

		[Browsable(true)]
		public Image OffBackground {
			get { return mOffBackground; }
			set {
				mOffBackground = value;
				Invalidate();
			}
		}

		[Browsable(true)]
		public bool IsOn {
			get {
				return mIsOn;
			}
			set {
				bool oldOn = mIsOn;
				mIsOn = value;
				if (oldOn != mIsOn) {
					Invalidate();
					if (OnToggleChanged != null) {
						OnToggleChanged(this, EventArgs.Empty);
					}
				}
			}
		}

		[Browsable(false)]
		public TextFormatFlags TextFormatFlags {
			get { return mTextFormatFlags; }
			private set {
				mTextFormatFlags = value;
				Invalidate();
			}
		}

		[Browsable(true)]
		[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
		public override string Text {
			get {
				return base.Text;
			}
			set {
				base.Text = value;
			}
		}

		public ToggleButton() {
			InitializeComponent();
			AutoScaleMode = System.Windows.Forms.AutoScaleMode.None;
		}

		protected override void OnPaintBackground(PaintEventArgs e) {
			base.OnPaintBackground(e);
			if (IsOn) {
				if(OnBackground != null)
					Sprite.Draw(e.Graphics, OnBackground, ClientRectangle, Padding);
			} else if (OffBackground != null) {
				Sprite.Draw(e.Graphics, OffBackground, ClientRectangle, Padding);
			}
		}

		protected override void OnPaint(PaintEventArgs e) {
			TextRenderer.DrawText(e.Graphics, Text, Font, new Rectangle(Padding.Left, Padding.Top, Width-Padding.Horizontal, Height-Padding.Vertical), ForeColor);
			base.OnPaint(e);
		}

		private void ToggleButton_MouseClick(object sender, MouseEventArgs e) {
			if (e.Button == System.Windows.Forms.MouseButtons.Left) {
				IsOn = !IsOn;
			}
		}
	}
}
